package pl.pkolodziej.platform.dao.user;

import java.util.List;

import org.apache.commons.lang.StringEscapeUtils;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import pl.pkolodziej.platform.vo.user.User;
import pl.pkolodziej.platform.vo.user.UserInfo;

@Repository
public class UserDAOImpl implements UserDAO {

	@Autowired
	private SessionFactory sessionFactory;
	
	@Autowired
	HibernateTemplate hibernateTemplate;

	public void addUser(User user, String group) {
		sessionFactory.getCurrentSession().save(user);
		UserInfo ui = new UserInfo();
		ui.setUsername(user.getUsername());
		ui.setGroup_id(group);
		sessionFactory.getCurrentSession().save(ui);
	}
	
	public void updatedUser(User user) {
		sessionFactory.getCurrentSession().update(user);
	}

	public List<User> listUsers() {
		return sessionFactory.getCurrentSession().createQuery("from User").list();
	}

	public void removeUser(Integer id) {
		User user = (User) sessionFactory.getCurrentSession().load(User.class, id);
		if (null != user) {
			sessionFactory.getCurrentSession().delete(user);
		}
	}
	
	public User getUserPassword(String username){
		try{
			return (User) hibernateTemplate.find("from User where username = '"+username+"'").get(0);	
		}catch (IndexOutOfBoundsException ie){
			return new User();
		}
	}
	
	public UserInfo getUserInfo(User user){
		User u = (User) hibernateTemplate.find("from User where username = ?",user.getUsername()).get(0);
		return u.getUserInfo();
	}
	
	public void updateUserInfo(UserInfo ui) {
		Query hql = sessionFactory.getCurrentSession().createQuery("update UserInfo set firstname=:_firstname" +
				" ,lastname = :_lastname" +
				" ,birthdate = :_birthdate" +
				" ,street = :_street" +
				" ,city = :_city" +
				" ,post = :_post" +
				" ,companyname = :_companyname" +
				" ,companyaddress = :_companyaddress" +
				" where username= :_username");
		
		hql.setParameter("_username", ui.getUsername());
		hql.setParameter("_firstname", StringEscapeUtils.escapeHtml(ui.getFirstname()));
		hql.setParameter("_lastname",StringEscapeUtils.escapeHtml(ui.getLastname()));
		hql.setParameter("_birthdate", StringEscapeUtils.escapeHtml(ui.getBirthdate()));
		hql.setParameter("_street", StringEscapeUtils.escapeHtml(ui.getStreet()));
		hql.setParameter("_city", StringEscapeUtils.escapeHtml(ui.getCity()));
		hql.setParameter("_post", StringEscapeUtils.escapeHtml(ui.getPost()));
		hql.setParameter("_companyname", StringEscapeUtils.escapeHtml(ui.getCompanyname()));
		hql.setParameter("_companyaddress", StringEscapeUtils.escapeHtml(ui.getCompanyaddress()));
		
		hql.executeUpdate();
	}
	
}
